package com.dun.re.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.dun.re.vo.Expenditure;

@Repository
public class ExpenditureDAOImpl implements ExpenditureDAO { 

	private HibernateTemplate template;
	private Session session;

	/**
	 * getting session, template
	 * 
	 * @param sessionFactory
	 */

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.template = new HibernateTemplate(sessionFactory);
		this.session = this.template.getSessionFactory().openSession();
	}

	/**
	 * method is used to save values to DB
	 * 
	 * @param expenditure
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public int save(Expenditure expenditure) {
		template.save(expenditure);
		return (Integer) session.createCriteria(Expenditure.class).list().size();
	}

	/**
	 * getting all expenditures details
	 */
	@SuppressWarnings("unchecked")
	public List<Expenditure> getExpenditures() {
		List<Expenditure> expenditureList = session.createCriteria(
				Expenditure.class).list();
		System.out.println(expenditureList.size());
		return expenditureList;
	}

	/**
	 * To retrieve expenditures based on the logged-in user
	 */
	@SuppressWarnings("unchecked")
	public List<Expenditure> getExpenditures(String loggedInUser) {
		List<Expenditure> expenditureList = session
				.createCriteria(Expenditure.class)
				.add(Restrictions.like("onWhom", loggedInUser)).list();
		return expenditureList;
	}

}
